package org.java.assembler;

import java.io.*;

public class Parser {

    private BufferedReader reader;
    private String statement;
    private CommandType commandType;
    private String symbol;
    private String dest;
    private String comp;
    private String jump;

    public Parser(File asmFile) {
        try {
            reader = new BufferedReader(new FileReader(asmFile));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public boolean hasMoreCommand() throws IOException {
        String line;
        while ((line = reader.readLine()) != null) {
            String trimLine = line.trim();
            if (!trimLine.isBlank() && !trimLine.startsWith("//")) {
                this.statement = trimLine;
                return true;
            }
        }
        return false;
    }

    public void advance() {
        reset();
        if (this.statement.startsWith("@")) {
            this.commandType = CommandType.A_COMMAND;
            this.symbol = this.statement.substring(1);
        } else if (this.statement.startsWith("(")) {
            // L命令
            this.commandType = CommandType.L_COMMAND;
            this.symbol = this.statement.substring(1, this.statement.indexOf(")"));
        } else {
            // C命令
            this.commandType = CommandType.C_COMMAND;
            if (this.statement.indexOf("=") != -1) {
                // 这是赋值语句
                String[] assignStatement = this.statement.split("=");
                this.dest = assignStatement[0].trim();
                this.comp = assignStatement[1].trim();
            } else if (this.statement.indexOf(";") != -1) {
                // 这是跳转语句
                String[] jumpStatement = this.statement.split(";");
                this.comp = jumpStatement[0].trim();
                this.jump = jumpStatement[1].trim();
            }
        }
    }

    private void reset() {
        this.symbol = null;
        this.dest = null;
        this.comp = null;
        this.jump = null;
    }

    public CommandType commandType() {
        return commandType;
    }

    public String symbol() {
        return this.symbol;
    }

    public String dest() {
        return this.dest;
    }

    public String comp() {
        return this.comp;
    }

    public String jump() {
        return this.jump;
    }
}
